<template>

  <div>
    <Card>
      <Row class="operation">
        <Button type="primary" size="large" icon="md-add" @click="openModel(2)">添加部门</Button>
        <Button size="large" icon="md-add" @click="openModel(1)">添加一级部门</Button>
        <Button size="large" icon="ios-trash" @click="removeDept()">批量删除</Button>
        <Button size="large" icon="ios-refresh-circle-outline" @click="reload">刷新</Button>
        <i-switch size="large">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch>
      </Row>
      <Row>
        <Col span="6">
          <Alert show-icon>当前编辑选择: <span
            v-if="selectDept!=null && selectDept.selected===true"><a>{{selectDept.title}}</a> <a
            @click="selectDept.selected=false">  取消选择</a></span></Alert>
          <AutoComplete
            v-model="searchTitle"
            :data="searchData"
            @on-search="handleSearch"
            placeholder="输入部门名搜索">
          </AutoComplete>
          <Tree :data="deptTree" ref="deptTree" show-checkbox @on-select-change="treeChange()"></Tree>
        </Col>
        <Col span="9">
          <Form :label-width="100" label-colon>
            <FormItem label="上级部门">
              <Row>
                <Col span="17"><Input size="large" clearable v-model="editFrom.parentTitle"></Input></Col>
                <Col>
                  <Poptip transfer trigger="click" placement="right-start" title="选择上级部门" width="240">
                    <Button size="large" style="margin-left: 20px" icon="md-list">选择部门</Button>
                    <div class="api" slot="content">
                      <Tree :data="JSON.parse(JSON.stringify(deptTree))" ref="deptTree" @on-select-change="parentDeptChange()"></Tree>
                    </div>
                  </Poptip>
                </Col>
              </Row>
            </FormItem>
            <FormItem label="部门名称" prop="name">
              <Input size="large" clearable v-model="editFrom.title"></Input>
            </FormItem>
            <FormItem label="部门负责人">
              <!--              {{this.editFrom.mainHeader}}-->
              <!--              {{this.editFrom.staffs}}-->
              <Select v-model="mainHeader" multiple>
                <Option v-for="item in this.editFrom.staffs" :value="item.id" :key="item.id">{{item.nickName}}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="副负责人">
              <!--              {{this.editFrom.viceHeader}}-->
              <Select v-model="viceHeader" multiple>
                <Option v-for="item in this.editFrom.staffs" :value="item.id" :key="item.id">{{ item.nickName}}
                </Option>
              </Select>
            </FormItem>
            <FormItem label="排序值">
              <Row>
                <Col sapn="3">
                  <InputNumber :max="100" :min="1" v-model="editFrom.sortOrder"></InputNumber>
                </Col>
              </Row>
            </FormItem>
            <FormItem label="是否启用">
              <i-switch size="large" v-model="editFrom.status" :true-value="0" :false-value="-1">
                <span slot="open">启用</span>
                <span slot="close">禁用</span>
              </i-switch>
            </FormItem>
            <FormItem>
              <Button type="primary" size="large" icon="ios-brush-outline" @click="editDept"> 修改并保存</Button>
              <Button size="large" @click="editFrom=JSON.parse(JSON.stringify($refs.deptTree.getSelectedNodes()[0]))"
                      style="margin-left: 8px">重置
              </Button>
            </FormItem>
          </Form>
        </Col>
      </Row>
    </Card>
    <Modal v-model="model.addModel" :title="model.addModelTitle">
      <Form ref="dept" :model="dept" :label-width="100" :rules="addValidate">
        <FormItem label="上级部门:" v-if="selectDept!=null && selectDept.selected===true && model.type===2">
          {{selectDept.title}}
        </FormItem>
        <FormItem label="部门名称:" prop="name">
          <Input placeholder="请输入部门名称" v-model="dept.name"></Input>
        </FormItem>
        <FormItem label="排序值:" prop="order">
          <Row>
            <Col sapn="3">
              <InputNumber :max="100" :min="1" v-model="dept.order"></InputNumber>
            </Col>
          </Row>
        </FormItem>
        <FormItem label="是否启用:" prop="status">
          <i-switch size="large" v-model="dept.status" :true-value="0" :false-value="-1">
            <span slot="open">启用</span>
            <span slot="close">禁用</span>
          </i-switch>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="addCancel">取消</Button>
        <Button type="primary" @click="addDept">提交</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { addDepartment, getTree, removeDept, listByDepartmentId, restartDept } from '@/api/user-api.js'

export default {
  name: 'department_list',
  data () {
    return {
      model: {
        addModel: false,
        type: 1,
        addModelTitle: '添加部门'
      },
      deptTree: [],
      dept: { status: 0, order: 1, name: '', parentId: 0 },
      ruleValidate: {
        name: [{ required: true, message: '部门名必填', trigger: 'blur' }]
      },
      addValidate: {
        name: [{ required: true, message: '部门名必填', trigger: 'blur' }],
        order: [{
          required: true,
          type: 'number',
          message: '排序值不能为空',
          trigger: 'change'
        }]
      },
      selectDept: {},
      searchTitle: '',
      searchData: [],
      editFrom: {},
      viceHeader: [],
      mainHeader: []
    }
  },
  created () {
    this.getByTree()
  },
  methods: {
    editDept () {
      this.editFrom.viceHeader = this.viceHeader
      this.editFrom.mainHeader = this.mainHeader
      let data = {
        id: this.editFrom.id,
        title: this.editFrom.title,
        parentId: this.editFrom.parentId,
        sortOrder: this.editFrom.sortOrder,
        status: this.editFrom.status,
        mainHeader: this.mainHeader,
        viceHeader: this.viceHeader
      }
      restartDept(data).then(res => {
        let data = res
        if (data.code === 200) {
          this.$Message.success('修改成功')
          this.getByTree()
        } else {
          this.$Message.warning(data.msg)
        }
      }).catch(err => {
        this.$Message.error('修改失败')
      })
    },
    /**
       *删除部门
       */
    removeDept () {
      let data = []
      this.$refs.deptTree.getCheckedNodes().forEach(v => {
        data.push(v.id)
      })
      removeDept(data).then(res => {
        if (res.code === 200) {
          this.reload()
        } else {
          this.$Message.warning(res.msg)
        }
      }).catch((err) => {
        this.$Message.error('请求失败')
      })
    },
    /**
       *刷新
       */
    reload () {
      Object.assign(this.$data, this.$options.data())
      this.getByTree()
    },
    /**
       * 添加部门
       */
    addDept () {
      this.$refs.dept.validate((valid) => {
        if (valid) {
          let data = {
            status: this.dept.status,
            title: this.dept.name,
            parentId: this.model.type === 1 ? this.dept.parentId : this.selectDept.id,
            sortOrder: this.dept.order
          }
          addDepartment(data).then((res) => {
            if (res.code === 200) {
              this.$Message.success(res.msg)
              this.model.addModel = false
              this.$refs.dept.resetFields()
              this.getByTree()
            } else {
              this.$Message.warning(res.msg)
            }
          }).catch((err) => {
            this.$Message.error('请求失败')
          })
        }
      })
    },

    /**
       * 取消添加部门
       */
    addCancel () {
      this.$refs.dept.resetFields()
      this.model.addModel = false
    },

    handleSearch (value) {
      this.searchData = []
      this.handleTree('', value, this.deptTree)
    },
    /**
       * 选择节点事件
       */
    treeChange () {
      let select = this.$refs.deptTree.getSelectedNodes()[0]
      if (select === undefined) {
        this.mainHeader = []
        this.viceHeader = []
        this.editFrom = {}
        return
      }
      this.selectDept = select
      this.editFrom = JSON.parse(JSON.stringify(this.selectDept))
      listByDepartmentId(select.id).then(res => {
        const data = res
        if (data.code === 200) {
          this.editFrom.staffs = data.data
          this.mainHeader = this.editFrom.mainHeader
          this.viceHeader = this.editFrom.viceHeader
        }
      })
    },
    /**
       * 获取部门树
       */
    getByTree () {
      this.deptTree = []
      getTree().then(res => {
        if (res.code === 200) {
          let tree = res.data
          this.deptTree = this.createTree(tree)
        } else {
          this.$Message.warning(res.msg)
        }
      }).catch((err) => {
        this.$Message.error('请求失败')
      })
    },

    /**
       * 修改上级部门
       */
    parentDeptChange () {
      let parent = this.$refs.deptTree.getSelectedNodes()[0]
      this.editFrom.parentId = parent.id
      this.editFrom.parentTitle = parent.title
    },

    /**
       * 打开添加窗口
       * */
    openModel (type) {
      this.$refs.dept.resetFields()
      this.model.type = type
      if (type === 1) {
        this.model.addModel = true
        return
      }
      if (this.selectDept != null && this.selectDept.selected === true) {
        this.model.addModel = true
        return
      }
      this.$Message.warning('请选择部门')
    },

    handleTree (prefix, value, list) {
      list.forEach(v => {
        v.ctitle = prefix === '' ? v.title : (prefix + '-' + v.title)
        if (v.title.indexOf(value) !== -1) {
          this.searchData.push(v.ctitle)
        }
        this.handleTree(v.ctitle, value, v.children)
      })
    },
    /**
       * 封装部门数
       * @param list list
       */
    createTree (list) {
      if (list === undefined) {
        return []
      }
      let tree = []
      list.forEach(v => {
        tree.push({
          title: v.title,
          expand: true,
          parentTitle: v.parentTitle,
          parentId: v.parentId,
          status: v.status,
          mainHeader: v.mainHeader,
          staffs: [],
          viceHeader: v.viceHeader,
          sortOrder: v.sortOrder,
          id: v.id,
          children: this.createTree(v.departments)
          // children: this.createTree(v.children)
        })
      })
      return tree
    }
  }
}
</script>
<style>
  .operation Button {
    margin: 8px;
  }
</style>
